Find the two elements that appear only once

Time: O(N); Space: O(1); medium

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice.

Find the two elements that appear only once.

Example 1:

Input: nums = [1, 2, 1, 3, 2, 5]

Output: [3, 5]

Notes:

  • The order of the result is not important.

  • So in the above example, [5, 3] is also correct.

  • Your algorithm should run in linear runtime complexity.

  • Could you implement it using only constant space complexity?

[1]:
import operator
from functools import reduce

class Solution1(object):
    def singleNumber(self, nums) -> list:
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        x_xor_y = reduce(operator.xor, nums)
        # print(x_xor_y)      # 6
        bit = x_xor_y & -x_xor_y
        # print(bit)          # 2
        result = [0, 0]
        for i in nums:
            result[bool(i & bit)] ^= i
            # print(result)
            # [1, 0]
            # [1, 2]
            # [0, 2]
            # [0, 1]
            # [0, 3]
            # [5, 3]
            # [5, 3]
        return result
[2]:
s = Solution1()
nums =  [1, 2, 1, 3, 2, 5]
assert s.singleNumber([1, 2, 1, 3, 2, 5]) == [5, 3] or [3, 5]
[3]:
class Solution2(object):
    def singleNumber(self, nums)  -> list:
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        x_xor_y = 0
        for i in nums:
            x_xor_y ^= i

        bit = x_xor_y & ~(x_xor_y - 1)

        x = 0
        for i in nums:
            if i & bit:
                x ^= i

        return [x, x ^ x_xor_y]
[4]:
s = Solution2()
nums =  [1, 2, 1, 3, 2, 5]
assert s.singleNumber([1, 2, 1, 3, 2, 5]) == [5, 3] or [3, 5]
[5]:
import collections

class Solution3(object):
    def singleNumber(self, nums)  -> list:
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        # print(sorted(collections.Counter(nums).items()))   # [(1, 2), (2, 2), (3, 1), (5, 1)]
        return [x[0] for x in sorted(collections.Counter(nums).items(), key=lambda i: i[1], reverse=False)[:2]]
[6]:
s = Solution3()
nums =  [1, 2, 1, 3, 2, 5]
assert s.singleNumber([1, 2, 1, 3, 2, 5]) == [5, 3] or [3, 5]